<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像
            webpack 读到写死的 src 就会帮我们把本地的图片打包到出口
            当遇到变量时, webpack 不会打包, 会直接将变量的值设置给 src
      -->
      <!-- img 的 src 只能设置两种数据: BASE64 (DataURL) 或 URL -->
      <img v-if="avatar" :src="avatar" alt="" class="preview" />
      <img
        v-else
        src="../../../assets/images/avatar.jpg"
        alt=""
        class="preview"
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- accept: 指定文件选择框可接受的文件类型 -->
        <input
          @change="avatarChange"
          accept="image/*"
          ref="fileInp"
          type="file"
          style="display: none"
        />
        <el-button
          @click="$refs.fileInp.click()"
          type="primary"
          icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          @click="uploadAvatar"
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },

  methods: {
    avatarChange(e) {
      const file = e.target.files[0]
      if (file) {
        console.log('用户的选择：', file)
        const fr = new FileReader()
        fr.readAsDataURL(file)
        fr.onload = (e) => {
          this.avatar = e.target.result
        }
      } else {
        console.log('用户取消了选择')
        this.avatar = ''
      }
    },
    async uploadAvatar() {
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$stoer.dispatch('user/getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
